package com.foo.SnapshotData;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.zip.DataFormatException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.cxf.aegis.type.encoded.TrailingBlocks;

import com.foo.CSVWriter.CSVWriterClient;
import com.foo.Entity.HistoricalData;
import com.foo.Entity.RealTimeData;
import com.foo.HistoricalData.HistoricalDataClient;
import com.foo.JSONWriter.JSONWriterClient;
import com.foo.ReadData.DataReceiver;
import com.foo.XMLWriter.XMLWriterClient;
import com.foo.constants.Constants;
import com.foo.constants.UIMessages;

/**
 * Servlet implementation class SnapshotDataServlett
 */
public class SnapshotDataServlett extends HttpServlet {
	private static final long serialVersionUID = 1L;	
	HistoricalData[] tickerdata =null;
	String[] trialstring = null;
	String fileName; 
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SnapshotDataServlett() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		HttpSession session = request.getSession(true);
		boolean downloadRequired = false;
		boolean readData = false;
		RequestDispatcher dispatcher;
		String filetype = "";
		try
		{
			String actbutton = request.getParameter("buttonHit");
			if(request.getParameter("TXT.x") != null)
			{
				filetype ="TXT";
				downloadRequired = true;
			}
			else if(request.getParameter("CSV.x")!= null)
			{
				filetype ="CSV";
				downloadRequired = true;
			}
			else if(request.getParameter("JSON.x")!= null)
			{
				filetype ="JSON";
				downloadRequired = true;
			}		
			else if(request.getParameter("XML.x")!= null)
			{
				filetype ="XML";
				downloadRequired = true;
			}
			if(downloadRequired)
			{
				HistoricalData[] sessionData = (HistoricalData[])session.getAttribute("SnapshotData");
				if(sessionData == null)
				{
					readData = true;
				}
			}
			else
			{
				readData = true;
			}
		
			
			if(readData) // Read Data from file
			{
				String tickername = request.getParameter("tickerSymbol");
				String timeperiod = request.getParameter("Time");
				DataReceiver receive = new DataReceiver();
					
				//Validate if all the input string entered
				if((tickername.equalsIgnoreCase(""))||(timeperiod.equalsIgnoreCase("")))
				{
					request.setAttribute("ServerMessage", UIMessages.REQUIRED_FIELD);
					dispatcher = getServletContext().getRequestDispatcher("/snapshot.jsp");
					dispatcher.forward(request, response);
				}
	   	 	
				SnapshotDataClient client = new SnapshotDataClient();
	   	 	
				java.sql.Date sqltoDate = null;
				java.sql.Date sqlfromDate = null;
				
				if(timeperiod.equals("OneWeek"))
				{
					/*// from current date to 1 week, use this.
					java.util.Date date = new java.util.Date();
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(date);
					calendar.add(Calendar.DAY_OF_YEAR, -7);
					java.util.Date toDate = calendar.getTime();
					java.util.Date fromDate = new java.util.Date();
					
					java.sql.Date sqltoDate = new java.sql.Date(toDate.getTime());
					java.sql.Date sqlfromDate = new java.sql.Date(fromDate.getTime());
					*/
					sqltoDate = java.sql.Date.valueOf("2009-11-20");
					sqlfromDate = java.sql.Date.valueOf("2009-11-13");
					
				}
				else if(timeperiod.equals("OneMonth"))
				{
					/*//for current date to 1 month use this.
					java.util.Date date = new java.util.Date();
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(date);
					calendar.add(Calendar.DAY_OF_YEAR, -30);
					java.util.Date fromDate = calendar.getTime();
					java.util.Date toDate = new java.util.Date();
					java.sql.Date sqltoDate = new java.sql.Date(toDate.getTime());
					java.sql.Date sqlfromDate = new java.sql.Date(fromDate.getTime());
					*/
					
					sqltoDate = java.sql.Date.valueOf("2009-11-20");
					sqlfromDate = java.sql.Date.valueOf("2009-10-20");	
				}
				else if(timeperiod.equals("TwoMonths"))
				{
					/*// from current date to two months, use this block
					java.util.Date date = new java.util.Date();
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(date);
					calendar.add(Calendar.DAY_OF_YEAR, -60);
					java.util.Date fromDate = calendar.getTime();
					java.util.Date toDate = new java.util.Date();
					java.sql.Date sqltoDate = new java.sql.Date(toDate.getTime());
					java.sql.Date sqlfromDate = new java.sql.Date(fromDate.getTime());
					*/
					
					sqltoDate = java.sql.Date.valueOf("2009-11-20");
					sqlfromDate = java.sql.Date.valueOf("2009-09-20");
				}
				else if(timeperiod.equals("ThreeMonths"))
				{
					/*// from current date to 3 months, use this.
					java.util.Date date = new java.util.Date();
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(date);
					calendar.add(Calendar.DAY_OF_YEAR, -90);
					java.util.Date fromDate = calendar.getTime();
					java.util.Date toDate = new java.util.Date();
					java.sql.Date sqltoDate = new java.sql.Date(toDate.getTime());
					java.sql.Date sqlfromDate = new java.sql.Date(fromDate.getTime());
					*/
					
					sqltoDate = java.sql.Date.valueOf("2009-11-20");
					sqlfromDate = java.sql.Date.valueOf("2009-08-20");
				}	
		   	 	//Sending request to topic
		   	 	client.sendsnapshotinfo(tickername,timeperiod,sqlfromDate,sqltoDate);
		   	 			   	 	
		   	 	//Receiving Client reply
		   	 	trialstring = receive.readtickerinfodata();
				if(trialstring != null)
				{
					System.out.println("values length: " +trialstring.length);
					int tickerlength = trialstring.length/7;
					tickerdata = new HistoricalData[tickerlength];
	
					tickerdata = new HistoricalData[trialstring.length];
					string_to_object(trialstring,tickerlength);
				}
				if(tickerdata != null)
				{
					session.removeAttribute("SnapshotData");
					session.setAttribute("SnapshotData", tickerdata);
					session.setAttribute("SnapshotDataString",trialstring);
					dispatcher = getServletContext().getRequestDispatcher("/snapshot.jsp");
					dispatcher.forward(request, response);
				}
				else
				{
					request.setAttribute("ServerMessage", UIMessages.NO_RECORD);
					dispatcher = getServletContext().getRequestDispatcher("/snapshot.jsp");
					dispatcher.forward(request, response);
				}
			}
			else if(downloadRequired) //Download Data
			{
				
				if(trialstring ==null || trialstring.length == 0)
				{
					trialstring = (String[])session.getAttribute("SnapshotDataString");
				}
				if(trialstring!=null && trialstring[0] != "" && filetype !=null)
				{
					if(filetype.equals("CSV"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						CSVWriterClient client = new CSVWriterClient();
						fileName =Constants.FILE_PATH + "data.csv";
						client.generateCSV(fileName, trialstring,"Snapshot");
						System.out.println("File Generate and stored in workspace folder: ");
						
						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
						response = downloadData(response,fileName);
						
						dispatcher = getServletContext().getRequestDispatcher("/snapshot.jsp");
						dispatcher.forward(request, response);
						System.out.println("File Generate and stored in workspace folder: ");
					}
					else if(filetype.equals("TXT"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						CSVWriterClient client = new CSVWriterClient();
						
						fileName =Constants.FILE_PATH + "data.txt";
						client.generateCSV(fileName, trialstring,"Snapshot");
						
						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
						response = downloadData(response,fileName);
						
						dispatcher = getServletContext().getRequestDispatcher("/snapshot.jsp");
						dispatcher.forward(request, response);
						System.out.println("File Generate and stored in workspace folder: ");
					}
					else if(filetype.equals("JSON"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						JSONWriterClient client = new JSONWriterClient();
						fileName =Constants.FILE_PATH + "data.json";
						client.generateJSON(fileName, trialstring,"Snapshot");
						System.out.println("File Generate and stored in workspace folder: ");
						
						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
						response = downloadData(response,fileName);
						
						dispatcher = getServletContext().getRequestDispatcher("/snapshot.jsp");
						dispatcher.forward(request, response);
						System.out.println("File Generate and stored in workspace folder: ");
					}
					else if(filetype.equals("XML"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						XMLWriterClient client = new XMLWriterClient();
						fileName =Constants.FILE_PATH + "data.xml";
						client.generateJSON(fileName, trialstring,"Snapshot");
						System.out.println("File Generate and stored in workspace folder: ");
						
						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
						response = downloadData(response,fileName);
						
						dispatcher = getServletContext().getRequestDispatcher("/snapshot.jsp");
						dispatcher.forward(request, response);
						System.out.println("File Generate and stored in workspace folder: ");
					}
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			request.setAttribute("ServerMessage", UIMessages.SERVICE_UNAVAILABLE);
			dispatcher = getServletContext().getRequestDispatcher("/snapshot.jsp");
			dispatcher.forward(request, response);
		}
		
	}
	
	
	public HttpServletResponse downloadData(HttpServletResponse response,String fileName) throws Exception
	{
		try
		{
			if(new File(fileName).exists())
			{
				File fileContent = new File(fileName);
				InputStream inputStream = new FileInputStream(fileContent);
				long length = fileContent.length();
				
			 if (length > Integer.MAX_VALUE) {
			        // File is too large
			    }
			 response.reset();
				response.setContentType("application/file");
				String name = new File(fileName).getName();
				System.out.println("File Name is :" + name);
				response.setHeader("Content-disposition","attachment; filename=" +name);
				   
			    byte[] bytes = new byte[(int)length];
	
			    int offset = 0,numRead = 0;
			    while (offset < bytes.length
			           && (numRead=inputStream.read(bytes, offset, bytes.length-offset)) >= 0) {
			        offset += numRead;
			        response.getOutputStream().write(bytes, 0, numRead);
			    }
	
			    if (offset < bytes.length) {
			        throw new IOException("Could not completely read file data.txt");
			    }
	
			    inputStream.close();
			}
			response.getOutputStream().flush();
			return response;
		}
		catch(Exception e)
		{
			throw e;
		}
	}
	
	public void string_to_object(String[] trialstring, int tickerarraysize)
	{
		int j=0;
		tickerdata = new HistoricalData[tickerarraysize];
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

			for(int i =0;i<trialstring.length;i+=7)
			{
				
				if(trialstring[i].equals("") || trialstring[i] == null)
				{
					System.out.println("No more data to print");
					break;
				}
				else
				{
					tickerdata[j]=new HistoricalData();
					try 
					{
						if(trialstring[i+1] != null)
						{
						System.out.println("Convery to date");
						java.util.Date dt = dateFormat.parse(trialstring[i+1]);
						java.sql.Date returndate=new java.sql.Date(dt.getTime());
						tickerdata[j].setDeals_date(returndate);
					}
					} 
					catch (ParseException e) 
					{
						e.printStackTrace();
					}
					tickerdata[j].setTicker_symbol(trialstring[i]);
					tickerdata[j].setOpen_value(Double.parseDouble(trialstring[i+2]));
					tickerdata[j].setHigh_value(Double.parseDouble(trialstring[i+3]));
					tickerdata[j].setLow_value(Double.parseDouble(trialstring[i+4]));
					tickerdata[j].setClose_value(Double.parseDouble(trialstring[i+5]));
					tickerdata[j].setVolume(Long.parseLong(trialstring[i+6]));
				
				System.out.println("values are: "+ tickerdata[j].getDeals_date() +tickerdata[j].getTicker_symbol()+ tickerdata[j].getOpen_value()+ tickerdata[j].getHigh_value()+ tickerdata[j].getLow_value()+ tickerdata[j].getClose_value()+ tickerdata[j].getVolume());
			
				j=j+1;
				}
			}
		System.out.println("Conversion to objectdata was successful");
	}
}

